package leetcode.primary;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class T139 {
    Set<String> wordDictSet;
    Set<Integer> indexSet;
    public boolean wordBreak(String s, List<String> wordDict) {
        wordDictSet = new HashSet<>(wordDict);
        indexSet = new HashSet<>();
        return DFS(0,s);
    }

    public boolean DFS(int start,String s){
        if (start==s.length()){
            return true;
        }
        for (int i = start+1; i <=s.length(); i++) {
            if (indexSet.contains(i))
                continue;
            if (wordDictSet.contains(s.substring(start,i))){
                if (DFS(i,s)){
                    return true;
                }
                indexSet.add(i);
            }
        }
        return false;
    }

    public static void main(String[] args) {
        T139 t139 = new T139();
        ArrayList<String > list = new ArrayList<>();
        list.add("cats");
        list.add("dog");
        list.add("sand");
        list.add("and");
        list.add("cat");
        System.out.println(t139.wordBreak("catsandog", list));
    }
}
